package install

import (
	"fmt"

	"github.com/gin-gonic/gin"

	"go-caipu/pkg/install/config"
	"go-caipu/pkg/install/routes"
	"go-caipu/pkg/setting"
)

func Init(cfg *setting.Cfg, path string) {

	config.InitConfig(path)
	// 创建gin引擎
	router := gin.Default()

	// 配置CORS
	router.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// 静态文件服务
	router.Static("/install", "./resources/install")

	// 设置路由
	routes.SetupRoutes(router)

	// 启动服务器
	port := cfg.Application.HTTPPort
	if port == "" {
		port = "8080"
	}

	fmt.Printf("Server is running on port %s\n", port)
	router.Run(fmt.Sprintf(":%s", port))
}
